/*
Copyright 2010-2011 CumulusCloud
http://cumuluscloud.cc

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cumulusCloud.knowledge;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Logger;

import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cumulusCloud.common.ManageSession;
import cumulusCloud.common.ManageUser;
import cumulusCloud.common.objects.CloudUser;

public class ServletFilterAuthenticationKnow implements javax.servlet.Filter {
	private Logger logger = java.util.logging.Logger.getLogger(ServletFilterAuthenticationKnow.class.getName());
	
	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;

		String userToken = ManageSession.getCurrentUserToken(httpServletRequest);
		
		logger.info("cloudusertoken: " + userToken);
		// Not logged in
		if ( (userToken == null)) {
			if (loginIfPossible(httpServletRequest, httpServletResponse)) {
				processPage(httpServletRequest, httpServletResponse);
			} 
			return;
		}
		
		// Logged in
		CloudUser user = ManageSession.getSessionUser(userToken);
		logger.info("User logged: " + user);
		// Verify valid
		if ( (user == null)) {
			if (loginIfPossible(httpServletRequest, httpServletResponse)) {
				processPage(httpServletRequest, httpServletResponse);
			} 
			return;
		}
		
		sendTokenCookie(userToken, httpServletResponse);
		chain.doFilter(request, response);
	}
	
	private boolean loginIfPossible(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String userToken = getLoginToken(request);
		
		if (userToken == null) {
			logginForm(request, response);
			return false;
		}
		
		logger.info("User successfully logged in");
		sendTokenCookie(userToken, response);
		
		return true;
	}

	private void sendTokenCookie(String userToken, HttpServletResponse response) {
		logger.info("Sending cookie");
		Cookie cookie = new Cookie("cloudusertoken", userToken);
		cookie.setPath("/");
		cookie.setMaxAge(86400);
		
		response.addCookie(cookie);
	}

	private String getLoginToken(HttpServletRequest request) {
		String user = request.getParameter("clouduser");
		String password = request.getParameter("cloudpassword");
		
		if ( (user == null) || (password == null)) {
			return null;
		}
		
		return ManageSession.createSession(user, password);
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}
	
	private void logginForm(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter pw = new PrintWriter(response.getOutputStream());
		pw.println("<html><head><title>ccSDK - Login</title></head><body>");
		pw.println("<p>Here is the user list with their password (this is only in the SDK version [of course]):</p>");
		pw.println("<table border=1><tr><th>Login</th><th>Password</th><th>Language</th><th>isAdmin</th></tr>");
		for (CloudUser user : ManageUser.listUsers()) {
			pw.println("<tr><td>" + user.name + "</td><td>" + user.password + "</td><td>" + user.language + "</td><td>" + user.isAdmin + "</td></tr>");
		}
		pw.println("</table>");
		pw.println("<form action='' method='post'>" +
				"<input type='text' name='clouduser' value='beta'>" +
				"<input type='text' name='cloudpassword' value='beta'>" +
				"<input type='submit' value='Go'>" +
				"</form>");
		pw.println("</body></html>");
		pw.close();
	}
	
	private void processPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
		PrintWriter pw = new PrintWriter(response.getOutputStream());
		pw.println("<html><head><meta http-equiv='refresh' content='1'><title>ccSDK - Login</title></head><body>");
		pw.println("<p>Sucessfully logged in. <a href=''>Process here</a></p>");

		pw.println("</body></html>");
		pw.close();
	}

}
